<template>
  <el-dialog
    v-model="visible"
    width="700px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    append-to-body
    class="unified-dialog batch-dialog-config"
  >
    <template #header>
      <DialogHeader
        icon="BellFilled"
        title="配置型批量操作示例"
        description="显示操作列表 + 详细配置表单"
        type="warning"
      />
    </template>
    
    <div class="bulk-info">
      <el-alert
        title="批量更新操作"
        type="warning"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>将更新以下 {{ items.length }} 条记录：</p>
          <ul class="item-list">
            <li v-for="item in items" :key="item.id || item.name">
              {{ item.name || item.topic_name }}
            </li>
          </ul>
        </template>
      </el-alert>
    </div>
    
    <div class="dialog-content" v-loading="loading">
      <el-form :model="form" label-width="140px">
        <el-form-item label="更新范围:">
          <el-radio-group v-model="form.updateScope">
            <el-radio 
              label="selected" 
              :disabled="items.length === 0"
            >
              仅更新选中的 {{ items.length }} 条记录
            </el-radio>
            <el-radio label="all">
              更新当前环境的全部记录（共{{ totalCount }}条）
            </el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-divider />
        
        <el-form-item label="操作间隔">
          <el-input-number
            v-model="form.interval"
            :min="1"
            :max="60"
            controls-position="right"
            style="width: 200px"
          />
          <span class="form-tip">秒，避免同时操作造成系统压力</span>
        </el-form-item>
        
        <el-form-item label="环境选择">
          <el-select
            v-model="form.environment"
            placeholder="选择环境"
            clearable
            filterable
            popper-append-to-body
            popper-class="batch-dialog-select-popper"
            style="width: 100%"
            @visible-change="handleSelectVisibleChange"
          >
            <el-option
              v-for="env in environmentOptions"
              :key="env.value"
              :label="`${env.label} (${env.host}:${env.port})`"
              :value="env.value"
            />
          </el-select>
          <span class="form-tip">选择操作环境，留空使用默认环境</span>
        </el-form-item>
        
        <el-form-item label="更新数据库">
          <el-switch
            v-model="form.update_db"
            active-text="是"
            inactive-text="否"
          />
          <span class="form-tip">多环境场景建议关闭，避免数据混乱</span>
        </el-form-item>
        
        <el-divider />
        
        <el-form-item label="告警阈值(小时):">
          <el-input-number 
            v-model="form.alert_threshold_hours" 
            :min="1" 
            :max="168"
            placeholder="请输入告警阈值"
            style="width: 200px"
          />
          <span class="form-tip">小时无新消息则触发告警</span>
        </el-form-item>
        
        <el-form-item label="Webhook URL:">
          <el-input 
            v-model="form.webhook_url" 
            placeholder="请输入企业微信/钉钉Webhook地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="首次告警时间:">
          <el-time-select
            v-model="form.alert_first_send_time"
            start="00:00"
            step="00:30"
            end="23:30"
            placeholder="选择首次告警发送时间"
            style="width: 200px"
            teleported
            popper-class="batch-dialog-select-popper"
          />
          <span style="margin-left: 10px; color: #909399;">建议设置在上班时间</span>
        </el-form-item>
        
        <el-form-item label="第2次告警间隔:">
          <el-input-number 
            v-model="form.alert_second_interval" 
            :min="60" 
            :max="86400"
            :step="3600"
            placeholder="秒"
            style="width: 200px"
          />
          <span v-if="form.alert_second_interval" style="margin-left: 10px; color: #909399;">
            秒（{{ formatSeconds(form.alert_second_interval) }}）
          </span>
          <span v-else style="margin-left: 10px; color: #909399;">秒</span>
        </el-form-item>
        
        <el-form-item label="第3次告警间隔:">
          <el-input-number 
            v-model="form.alert_third_interval" 
            :min="60" 
            :max="86400"
            :step="3600"
            placeholder="秒"
            style="width: 200px"
          />
          <span v-if="form.alert_third_interval" style="margin-left: 10px; color: #909399;">
            秒（{{ formatSeconds(form.alert_third_interval) }}）
          </span>
          <span v-else style="margin-left: 10px; color: #909399;">秒</span>
        </el-form-item>
        
        <el-form-item label="最大告警次数:">
          <el-input-number 
            v-model="form.max_alert_count" 
            :min="1" 
            :max="10"
            placeholder="次"
            style="width: 200px"
          />
          <span style="margin-left: 10px; color: #909399;">单周期内最多发送告警次数</span>
        </el-form-item>
      </el-form>
      
      <!-- 操作列表预览 -->
      <div v-if="items.length > 0 && form.updateScope === 'selected'" class="items-preview">
        <el-alert
          title="将更新以下记录"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <ul class="item-list">
              <li v-for="item in items.slice(0, 5)" :key="item.id || item.name">
                {{ item.name || item.topic_name }}
              </li>
              <li v-if="items.length > 5" class="more-items">
                还有 {{ items.length - 5 }} 条记录...
              </li>
            </ul>
          </template>
        </el-alert>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定更新
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import DialogHeader from '@/components/DialogHeader.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  items: {
    type: Array,
    default: () => []
  },
  totalCount: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)

// Mock 环境选项
const environmentOptions = ref([
  { label: '生产环境', value: 'prod', host: 'flink-prod.example.com', port: 8081 },
  { label: '测试环境', value: 'test', host: 'flink-test.example.com', port: 8082 },
  { label: '开发环境', value: 'dev', host: 'flink-dev.example.com', port: 8083 }
])

const form = ref({
  updateScope: 'selected',
  interval: 5,
  environment: '',
  update_db: false,
  alert_threshold_hours: 24,
  webhook_url: '',
  alert_first_send_time: '09:30',
  alert_second_interval: 7200,
  alert_third_interval: 21600,
  max_alert_count: 3
})

const handleSelectVisibleChange = (visible) => {
  const poppers = document.querySelectorAll('.batch-dialog-select-popper')
  console.log('[BatchDialogConfig] select visible ->', visible)
  console.log('[BatchDialogConfig] current poppers ->', poppers)
  poppers.forEach((popper, index) => {
    const styles = window.getComputedStyle(popper)
    console.log('[BatchDialogConfig] popper info', index, {
      display: styles.display,
      opacity: styles.opacity,
      visibility: styles.visibility,
      zIndex: styles.zIndex,
      pointerEvents: styles.pointerEvents,
      top: styles.top,
      left: styles.left
    })
  })
}

const formatSeconds = (seconds) => {
  if (!seconds) return ''
  if (seconds < 60) return `${seconds}秒`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`
  return `${Math.floor(seconds / 86400)}天`
}

const handleClose = () => {
  visible.value = false
}

const handleSubmit = async () => {
  loading.value = true
  
  const targetCount = form.value.updateScope === 'selected' ? props.items.length : props.totalCount
  
  // 模拟批量更新
  await new Promise(resolve => setTimeout(resolve, 800))
  
  ElMessage.success(`已成功更新 ${targetCount} 条记录的告警配置（演示模式）`)
  emit('success')
  handleClose()
  
  loading.value = false
}

// 监听对话框显示，重置表单
watch(visible, (newVal) => {
  if (newVal) {
    form.value = {
      updateScope: props.items.length > 0 ? 'selected' : 'all',
      interval: 5,
      environment: '',
      update_db: false,
      alert_threshold_hours: 24,
      webhook_url: '',
      alert_first_send_time: '09:30',
      alert_second_interval: 7200,
      alert_third_interval: 21600,
      max_alert_count: 3
    }
  }
})
</script>

<style scoped>
.bulk-info {
  margin-bottom: 20px;
}

.item-list {
  margin: 10px 0 0 0;
  padding-left: 20px;
  max-height: 150px;
  overflow-y: auto;
}

.item-list li {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}

.form-tip {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.items-preview {
  margin-top: 20px;
}

.item-list li.more-items {
  color: #909399;
  font-style: italic;
}
</style>

